import React, {Component} from 'react';
import {
    Alert,
    Button,
    FlatList,
    Image,
    NativeModules,
    StatusBar,
    StyleSheet,
    Text,
    ToastAndroid,
    View
} from 'react-native';
import * as Color from "../../../lib.xjs/constant/Color";
import TouchableItem from "react-navigation/src/views/TouchableItem";
import BizUser from "../../entity/BizUser";
import * as BizConstant from "../../constant/BizContant";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import {UUID} from "../../../lib.xjs/util/UUID";
import BottomPop from "../../../lib.xjs/widget/modal/BottomPop";
import TouchButton from "../../../lib.xjs/widget/btn/HighlightButton";
import {GaquUtil} from "../../util/GaquUtil";

const ITEM_HEIGHT = 120;
const ic_avatar_default = require('../../../../img/ic_mine_dis.png');

/** 仓体运动记录 */
export default class PersonExerciseList extends Component {

    mPopMenu: Array = ['充值', '积分管理', '联系他'];

    _mFlatList;

    /** 用户ID(之前页面传来) */
    mPersonId;

    /** 用户Name(之前页面传来) */
    mPersonName;

    /** 用户头像(查询得到) */
    mPersonAvatar;

    /** 用户手机号(查询得到) */
    mPersonMobile;

    /** 用户余额(查询得到) */
    mPersonBalance: 0;

    /** 用户积分(查询得到) */
    mPersonScore: 0;

    /** 用户状态 */
    mPersonStatus: 2;


    static navigationOptions = (props) => {
        const params = props.navigation.state.params;
        return {
            title: `${params.personName}`,
            headerRight: (                        //通过params为按钮绑定increase方法
                <Button onPress={() => params.navigatePress()} title=":"/>
            ),
        };
    };

    componentWillMount(): void {
        //在static中使用this方法
        this.props.navigation.setParams({navigatePress: () => this._onClickItemBtn()});
    };

    constructor(props) {
        super(props);
        this.state = {
            /** 是否正在刷新 */
            mIsRefresh: false,
            /** 数据源 */
            mDatas: [],
            /** foot提示信息 */
            loadMoreInfo: '正在加载',
        };

        this.mPersonId = this.props.navigation.state.params.personId;
        this.mPersonName = this.props.navigation.state.params.personName;
    }

    componentDidMount(): void {
        this._getDatas(new Date(), 20, false);
    }

    /** 点击toolbar右键 */
    _onClickItemBtn = () => {
        this._showPop();
    };

    /** 显示 */
    _showPop = () => {
        this.refs.pop.setDatasAndShow("请选择操作", this.mPopMenu);
    };

    /** 点击回调 */
    _onClick(index: number) {
        switch (index) {
            case 0: {
                this.props.navigation.navigate('PersonCharge', {
                    personName  : this.mPersonName,
                    personId    : this.mPersonId,
                    currBalance : this.mPersonBalance,
                    callback: (data) => {
                    }
                });
                break
            }

            case 1: {
                this.props.navigation.navigate('PersonMarkerManage', {
                    personName  : this.mPersonName,
                    personId    : this.mPersonId,
                    personMarker: this.mPersonScore,
                    callback: (data) => {
                    }
                });
                break
            }

            case 2: {
                if(!NativeModules.NativeMethods || !this.mPersonMobile) return;
                NativeModules.NativeMethods.callSb(this.mPersonMobile);
                break
            }
        }
    };

    render() {
        return (
            <View style={{flex: 1, backgroundColor: Color.windowWhite}}>
                <StatusBar
                    hidden={false}
                    translucent={false}
                    backgroundColor={Color.colorPrimaryDark}/>

                <FlatList
                    ref={(flatList) => this._mFlatList = flatList}
                    ListFooterComponent={this._footer()}

                    data={this.state.mDatas}
                    renderItem={(item) => {
                        return this._renderItem(item)
                    }}
                    // ItemSeparatorComponent={this._separator}
                    keyExtractor={(item, index) => ("index" + index + item)}

                    refreshing={this.state.mIsRefresh}
                    onRefresh={this._onRefresh}

                    getItemLayout={this.getItemLayout}

                    onEndReachedThreshold={0.000001}
                    onEndReached={this._onReachEnd}/>
                <HttpHelper ref={'http'}/>
                <BottomPop ref="pop" onClick={(index: number) => this._onClick(index)}/>
            </View>
        );
    }

    /**
     * 可选优化项。但是实际测试中，如果不做该项优化，性能会差很多。
     * 所以强烈建议做此项优化！如果不做该项优化，每个列表都需要事先渲染一次，动态地取得其渲染尺寸，然后再真正地渲染到页面中。
     * 如果预先知道列表中的每一项的高度(ITEM_HEIGHT)和其在父组件中的偏移量(offset)和位置(index)，就能减少一次渲染。
     * 这是很关键的性能优化点
     * @param data
     * @param index
     * @returns {{length: number, offset: number, index: *}}
     */
    getItemLayout = (data, index) => {
        return {length: ITEM_HEIGHT, offset: (ITEM_HEIGHT + 2) * index, index}
    };

    /**
     * 将列表元素和数据结合在一起，生成列表。
     * @param item 是data属性中的每个列表的数据（ Array<object> 中的 object) 。
     */
    _renderItem = (item) => {
        if (item.item.endTime) {
            return this._getItemView_NotING(item);
        } else return this._getItemView_ING(item);
    };

    _getItemView_NotING = (item) => {
        return <View style={styles.item_layout_touch_bg}>
            <TouchableItem onPress={() => this._onClickItem(item)}>
                <View style={styles.item_not_ing}>

                    <View style={styles.item_not_ing_line1}>
                        <View style={{flexDirection:'row', justifyContent: 'flex-start', alignItems: 'center'}}>
                            <Text style={{fontSize: 18, color: Color.black}}>{this.mPersonName}</Text>
                            <Text style={[styles.cabin_status_text, {backgroundColor: GaquUtil.getPersonStatusColor(this.mPersonStatus)}]}>{GaquUtil.getPersonStatusName(this.mPersonStatus)}</Text>
                        </View>

                        <Text style={{
                            fontSize: 18,
                            color: Color.black
                        }}>{this.mPersonMobile}</Text>
                    </View>

                    <View style={[styles.item_not_ing_line1, {marginTop: 5}]}>
                        <Text style={{fontSize: 14}}>仓体</Text>
                        <Text style={{fontSize: 14}}>{item.item.cangName}</Text>
                    </View>

                    <View style={styles.item_not_ing_line1}>
                        <Text style={{fontSize: 14}}>花费</Text>
                        <Text style={{fontSize: 14}}>{item.item.money}元</Text>
                    </View>

                    <View style={styles.item_not_ing_line1}>
                        <Text style={{fontSize: 14}}>运动时间</Text>
                        <Text
                            style={{fontSize: 14}}>{GaquUtil.getTimeDifference(item.item.beginTime, item.item.endTime)}分钟</Text>
                    </View>

                    <View style={styles.item_not_ing_line1}>
                        <Text style={{fontSize: 14}}>{item.item.beginTime}</Text>
                        <Text style={{fontSize: 14}}> — </Text>
                        <Text style={{fontSize: 14}}>{item.item.endTime} </Text>
                    </View>
                </View>
            </TouchableItem>
        </View>
    };

    _getItemView_ING = (item) => {
        return <View style={styles.item_layout_touch_bg}>
            <TouchableItem onPress={() => this._onClickItem(item)}>
                <View style={[styles.item_ing]}>

                    <View style={styles.content_title}>
                        <View style={{height: '80%', width:8, backgroundColor: Color.colorPrimaryLight, marginRight: 15,}}/>
                        <Text style={{fontSize: 18, color: Color.black}}>正在运动</Text>
                    </View>

                    <View style={{width: '100%', height: 0.5, backgroundColor: Color.lightGray}}/>

                    <View style={styles.item_ing_line1}>
                        <Image style={styles.item_head}
                               source={this.mPersonAvatar === null ? ic_avatar_default : {uri: this.mPersonAvatar}}
                               resizeMode={Image.resizeMode.center}/>
                        <View
                            style={{
                                flexDirection: 'column',
                                justifyContent: 'center',
                                alignItems: 'flex-start',
                                marginLeft: 15,
                                flex: 1,
                            }}>

                            <View style={{flexDirection:'row', justifyContent: 'flex-start', alignItems: 'center'}}>
                                <Text style={{fontSize: 18}}>{this.mPersonName}</Text>
                                <Text style={[styles.cabin_status_text, {backgroundColor: GaquUtil.getPersonStatusColor(this.mPersonStatus)}]}>{GaquUtil.getPersonStatusName(this.mPersonStatus)}</Text>
                            </View>

                            <Text style={{fontSize: 16}}>{this.mPersonMobile}</Text>
                            <Text style={styles.icon_text}>余额: {this.mPersonBalance}元</Text>
                            <Text style={styles.icon_text}>积分: {this.mPersonScore}分</Text>
                        </View>
                    </View>

                    <View style={{width: '100%', height: 0.5, backgroundColor: Color.lightGray}}/>

                    <View
                        style={{
                            width: '100%',
                            flexDirection: 'row',
                            justifyContent: 'space-between',
                            marginVertical: 8,
                        }}>
                        <View
                            style={{
                                flex: 1,
                                flexDirection: 'column',
                                justifyContent: 'center',
                                alignItems: 'flex-start'
                            }}>
                            <Text style={{fontSize: 14}}>开始时间</Text>
                            <Text style={{fontSize: 14}}>{item.item.beginTime} </Text>
                        </View>

                        <View style={{width: 0.5, backgroundColor: Color.lightGray, marginHorizontal: 10,}}/>

                        <View
                            style={{
                                flex: 1,
                                flexDirection: 'column',
                                justifyContent: 'center',
                                alignItems: 'flex-start'
                            }}>
                            <Text style={{fontSize: 14}}>结束时间</Text>
                            <Text style={{fontSize: 14}}>{item.item.endTime} </Text>
                        </View>
                    </View>

                    <View style={{width: '100%', height: 0.5, backgroundColor: Color.lightGray}}/>

                    <View style={styles.line_layout}>
                        <TouchButton styleTouch={styles.buttonTouch} underlayColor={Color.colorPrimary}
                                     styleText={styles.buttonText} title={'结束运动'}
                                     onPress={() => {
                                         Alert.alert(
                                             '确认框',
                                             '确定结束运动?',
                                             [
                                                 {text: '确定',    onPress: () => { this._doEndSport(item) } },
                                             ],
                                             { cancelable: true }
                                         )
                                     }}/>
                        <TouchButton styleTouch={styles.buttonTouch} underlayColor={Color.colorPrimary}
                                     styleText={styles.buttonText} title={'撤销订单'}
                                     onPress={() => {
                                         Alert.alert(
                                             '确认框',
                                             '确定撤销订单?',
                                             [
                                                 {text: '确定',    onPress: () => { this._doCancelOrder(item) } },
                                             ],
                                             { cancelable: true }
                                         )
                                     }}/>
                    </View>
                </View>
            </TouchableItem>
        </View>
    };

    /** 分割线 */
    _separator() {
        return <View style={{height: 1, backgroundColor: Color.lightGray}}/>;
    };

    /** 尾 */
    _footer() {
        return <View style={{flexDirection: 'column', backgroundColor: Color.windowWhite}}>
            <View style={{height: 0.5, backgroundColor: Color.lightMoreGray}}/>
            <Text style={[styles.txt]}>{this.state.loadMoreInfo}</Text>
        </View>;
    };

    /** 获取数据 */
    _getDatas(lastTime: Date, count: number, isClear: boolean): void {
        if (!this.refs.http) return;
        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("lastTime", lastTime.Format("yyyy-MM-dd hh:mm:ss"));
        body.set("count", count);
        body.set("userId", this.mPersonId);

        this.refs.http.setURL(BizConstant.GET_EXERCISE_RECORD_PERSON)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                if (!res.data.records) return;

                // 初始化全局变量
                let datas = res.data.records;
                if (!isClear) datas = [...this.state.mDatas, ...datas];

                if (res.data.user) {
                    console.log("--------------res.data.user");
                    console.log(res.data.user);
                    this.mPersonAvatar = res.data.user.headImg;
                    this.mPersonMobile = res.data.user.mobile;
                    this.mPersonBalance = res.data.user.balance;
                    this.mPersonScore = res.data.user.score;
                    this.mPersonStatus = res.data.user.status;
                }

                this.setState({
                    mDatas: datas,
                    loadMoreInfo: res.data.records.length < 20 ? '---已经到底了---' : '正在加载',
                });
            })
            .setTimeout(10 * 1000)
            .start(false);
    }

    /** 下拉时促发 */
    _onRefresh = () => {
        if (this.state.mIsRefresh) return;
        ToastAndroid.show('正在刷新中.... ', ToastAndroid.SHORT);
        this.setState({
            mIsRefresh: true,
        });

        let timer = setTimeout(() => {
            this.setState({
                mIsRefresh: false,
            });
            this._getDatas(new Date(), 20, true);
            clearTimeout(timer);
        }, 1000)
    };

    /** 拉到底部时促发 */
    _onReachEnd = () => {
        this._getDatas(this._getLastTimeFromList(), 20, false);
    };

    _onClickItem = (item): void => {
    };

    /** 从列表中获取最晚的时间 */
    _getLastTimeFromList(): Date {
        let earistTime: Date = new Date();
        for (let item of this.state.mDatas) {
            if (!item.beginTime) continue;
            let timeTarget: Date = new Date(item.beginTime.replace(/-/g, "\/"));
            console.log(timeTarget);
            if (timeTarget < earistTime) earistTime = timeTarget;
        }
        return earistTime;
    }

    /** 结束运动 */
    _doEndSport(item): void {
        if (!this.refs.http) return;
        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("recordId", item.item.id);

        this.refs.http.setURL(BizConstant.GET_END_SPORT)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("正在结束")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                ToastAndroid.show('结束运动成功', ToastAndroid.SHORT);
                this._onRefresh();
            })
            .setTimeout(10 * 1000)
            .start(true);
    }

    /** 撤销订单 */
    _doCancelOrder(item) {
        if (!this.refs.http) return;
        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("recordId", item.item.id);

        this.refs.http.setURL(BizConstant.GET_CANCEL_ORDER)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("正在撤销")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                ToastAndroid.show('撤销订单成功', ToastAndroid.SHORT);
                this._onRefresh();
            })
            .setTimeout(10 * 1000)
            .start(true);
    }
}

const styles = StyleSheet.create({
    txt: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: Color.darkGray,
        fontSize: 14,
    },

    item_layout_touch_bg: {
        marginHorizontal: 5,
        marginVertical: 5,
        borderRadius: 4,
        borderWidth: 0.5,
        borderColor: Color.lightMoreGray,
        backgroundColor: Color.windowWhiteLight,
    },

    item_not_ing: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        height: ITEM_HEIGHT + 2,
        paddingHorizontal: 10,
    },

    item_not_ing_line1: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },

    item_ing: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        paddingHorizontal: 10,
    },

    item_ing_line1: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
    },

    item_head: {
        height: 100,
        width: 100,
        borderRadius: 100,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },

    icon_text: {
        flexDirection: 'row',
        justifyContent: 'center',
        fontSize: 14,
        color: Color.white,
        backgroundColor: Color.colorPrimaryLight,
        paddingHorizontal: 4,
        borderRadius: 5,
        marginTop: 5,
    },

    line_layout: {
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingHorizontal: 5,
        paddingVertical: 5,
    },

    buttonTouch: {
        width: "45%",
        backgroundColor: Color.colorPrimaryLight,
    },

    buttonText: {
        fontSize: 16,
        color: Color.white,
        paddingVertical: 5,
    },

    content_title: {
        height: 25,
        width: '100%',
        flexDirection:'row',
        justifyContent: 'flex-start',
        alignItems: 'center',
        margin: 5,
    },

    cabin_status_text: {
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 14,
        borderRadius: 4,
        paddingHorizontal: 4,
        marginLeft: 3,
        color: Color.white,
    },
});
